#!/bin/bash
#自动化配置mysql主从复制(双主双从)

master="mysql2-master"
master_ip="192.168.33.10"
slaves=(mysql2-slave)

#数据库密码
mysql_pwd="fangzq"
grant_user="deng" #授权用户名
grant_pwd="123456"

#获取容器的端口号
get_port(){
	docker inspect $1 | grep HostPort | awk -F'"' 'NR==1{print $4}'
}

#生成slave配置master语句

#-e后面要加双引号
get_master(){
	conn_cmd='mysql -uroot -p'${mysql_pwd}' -e "'
	slave_master="CHANGE MASTER TO MASTER_HOST='$4',
        MASTER_USER='${grant_user}',
        MASTER_PASSWORD='${grant_pwd}',
        MASTER_LOG_FILE='$2',
        MASTER_LOG_POS=$3,master_port=$(get_port $1);start slave;"
    conn_cmd+=$slave_master
    conn_cmd+='"'
}

#配置从服务器信息
set_slave(){
	status=`docker exec $1 sh -c "mysql -uroot -p$mysql_pwd -e 'show master status'"`
	file=$(echo $status | awk '{print $6}')
	position=`echo $status | awk '{print $7}'`
	for slave in $2;do
		get_master $1 $file $position $3
		docker exec $slave sh -c "$conn_cmd"  #注意这里的引号
		echo "服务器$1配置结果：\n"
		docker exec $slave sh -c "mysql -uroot -p${mysql_pwd} -e 'show slave status \G'" | grep "Running"
	done
}

#为每一个master建立授权用户
grant='GRANT REPLICATION SLAVE ON *.* TO "'$grant_user'"@"%" IDENTIFIED BY "'$grant_pwd'"; FLUSH PRIVILEGES;'
docker exec $master sh -c "mysql -uroot -p$mysql_pwd -e '$grant'"


#配置从服务器信息
set_slave $master ${slaves[@]} $master_ip


